/*
 * @Author: yangrongxin
 * @Date: 2021-08-03 11:11:42
 * @LastEditors: liubin
 * @LastEditTime: 2021-11-16 14:38:21
 */
import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { ScrollView, View, Text } from '@tarojs/components';
import { getEvalutionClass, getArticleClass } from '@/services/dicts';
import styles from './index.module.less';

enum CLASS_TYPE {
  CEPING = 1, // 测评
  HUANJIAO = 2, // 宣教
}

const EvaluationClass = (props: any, ref: any) => {
  const { onChange, type = CLASS_TYPE.CEPING } = props;

  const [selectedIndex, setSelectedIndex] = useState();
  const [classList, setClassList] = useState<any[]>([]);

  let valueField: string = ''; // 当前展示的值字段
  let labelField: string = ''; // 当前展示的label字段
  let requestFn; // 当前的请求方法

  if (type === CLASS_TYPE.CEPING) {
    valueField = 'measureTableCategoryId';
    labelField = 'name';
    requestFn = getEvalutionClass;
  }

  if (type === CLASS_TYPE.HUANJIAO) {
    valueField = 'moduleCode';
    labelField = 'moduleName';
    requestFn = getArticleClass;
  }

  const getData = (isfirstload = false) => {
    if (requestFn)
      requestFn().then((res: any) => {

        if (Array.isArray(res)) {
          const navBars = type === CLASS_TYPE.HUANJIAO ? [
            {
              moduleName: '全部',
              moduleCode: ''
            },
            ...res,
          ] : [...res];

          setClassList(navBars);
          if (isfirstload) {
            setSelectedIndex(navBars[0][valueField]);
            onChange && onChange(navBars[0][valueField]);
          }
        }
      });
  };

  useEffect(() => {
    getData(true);
  }, []);

  useImperativeHandle(ref, () => ({
    reload: () => getData(),
  }));

  return (
    <ScrollView scrollX scrollWithAnimation className={styles.wapper}>
      <View className={styles.itemWapper}>
        {classList.map((item: any) => {
          const value = item[valueField];
          const label = item[labelField];
          return (
            <View
              key={String(value)}
              className={`${selectedIndex === value ? styles.checked : ''}`}
              onClick={() => {
                onChange && onChange(value);
                setSelectedIndex(value);
              }}
            >
              <Text>{label}</Text>
            </View>
          );
        })}
      </View>
    </ScrollView>
  );
};

export default forwardRef(EvaluationClass);
export { CLASS_TYPE };
